24. 练习 — 更多循环变量 (1/2)

练习 — 更多循环变量 (1/2)

你刚刚编写了绘制三个彩色线条的代码,如下所示:

你可能发现了,代码重复性很高。我们看看能否使用 for 循环降低重复性,并画出三个短线。

使每条线颜色都不同可能有点麻烦,我们(暂时)简化下并使所有线条都是红色。

下面的 workspace 中的代码将画出三个红色线条,中间有间隙。可以看出,某些代码重复了。请更改代码,使这些代码行位于 for 循环里。

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: html-live
  • Opened files (when workspace is loaded): n/a

备注 :如果你无法打开上面的workspace,请去 这里


## ⚠️ 剧透! **下面是我们的解决方案。**如果你能认真完成练习,然后再将你的代码与我们的代码进行对比,学习效果将更好!

----

解决方案

如果你的代码可行,应该看起来如下所示:

import turtle
amy = turtle.Turtle()

# Make the width thicker so that the line will be easier to see
# 使线条宽度加粗,以便更容易看到线条
amy.width(5)

# Move back without drawing anything
# 向后移动且不画任何东西
amy.penup()
amy.back(140)
amy.pendown()

# Draw three red lines, with space in between
#绘制三条红线,线与线之间用空格间隔
for line in [1, 2, 3]:
    amy.color("red")
    amy.forward(50)
    amy.penup()
    if line != 3:
        amy.forward(50)
    amy.pendown()

我们将在下个页面继续使用此代码。